package com.erhuogo.action;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.erhuogo.bean.GridPageBean;
import com.erhuogo.bean.MemCommoBean;
import com.erhuogo.bean.PageBean;
import com.erhuogo.bean.Response;
import com.erhuogo.entity.CommodityInfo;
import com.erhuogo.entity.Favorite;
import com.erhuogo.entity.Member;
import com.erhuogo.enumerate.Result;
import com.erhuogo.service.CommodityInfoService;
import com.erhuogo.service.MemberService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

/**
 * 会员Action
 * 
 * @author aibinxiao
 * @date 2016年10月9日 下午4:17:40
 */
public class MemberAction extends ActionSupport{

	private static final long serialVersionUID = 6654517304306191870L;
	private static Logger logger = LoggerFactory.getLogger(MemberAction.class);
	private String deleteMsg;
	public String getDeleteMsg() {
		return deleteMsg;
	}

	public void setDeleteMsg(String deleteMsg) {
		this.deleteMsg = deleteMsg;
	}

	private File portrait; //头像文件
	private String portraitFileName; //头像文件名
	private String pageNum; //页码
	private PageBean pageBean;
	

	public PageBean getPageBean() {
		return pageBean;
	}

	public void setPageBean(PageBean pageBean) {
		this.pageBean = pageBean;
	}

	public String getPageNum() {
		return pageNum;
	}

	public void setPageNum(String pageNum) {
		this.pageNum = pageNum;
	}

	public File getPortrait() {
		return portrait;
	}

	public void setPortrait(File portrait) {
		this.portrait = portrait;
	}

	public String getPortraitFileName() {
		return portraitFileName;
	}

	public void setPortraitFileName(String portraitFileName) {
		this.portraitFileName = portraitFileName;
	}

	// 模型驱动使用的对象
	private Member member;
	
	public Member getMember() {
		return member;
	}

	public void setMember(Member member) {
		this.member = member;
	}
	
	// 注入MemberService
	private MemberService memberService;
	private CommodityInfoService commodityInfoService;
	private List<MemCommoBean> memComms=new ArrayList<MemCommoBean>();
	private CommodityInfo comm;
	private Favorite favo;
	private MemCommoBean memComm;
	
	public CommodityInfoService getCommodityInfoService() {
		return commodityInfoService;
	}

	public void setCommodityInfoService(CommodityInfoService commodityInfoService) {
		this.commodityInfoService = commodityInfoService;
	}

	
	public MemCommoBean getMemComm() {
		return memComm;
	}

	public void setMemComm(MemCommoBean memComm) {
		this.memComm = memComm;
	}

	public Favorite getFavo() {
		return favo;
	}

	public void setFavo(Favorite favo) {
		this.favo = favo;
	}

	public CommodityInfo getComm() {
		return comm;
	}

	public void setComm(CommodityInfo comm) {
		this.comm = comm;
	}

	public List<MemCommoBean> getMemComms() {
		return memComms;
	}

	public void setMemComms(List<MemCommoBean> memComms) {
		this.memComms = memComms;
	}

	public void setMemberService(MemberService memberService) {
		this.memberService = memberService;
	}
	
	public MemberService getMemberService() {
		return memberService;
	}
	
	// 判断用户是否注册的手机号
	private String telephone;

	public String getTelephone() {
		return telephone;
	}

	public void setTelephone(String telephone) {
		this.telephone = telephone;
	}
	
	// 返回页面数据
	private Response response = new Response();

	public Response getResponse() {
		return response;
	}

	public void setResponse(Response response) {
		this.response = response;
	}

	/**
	 * 1.跳转到登录页面
	 */
	public String loginPage() {
		return "loginPage";
	}
	
	/**
	 * 2.登录的方法
	 */
	public String login() {
		Member existMember = memberService.login(member.getPhoneNumber(), member.getPassword());
		// 判断
		if (existMember == null) {
			return "toLogin";
		} else {
			ServletActionContext.getRequest().getSession().setAttribute("existUser", existMember);
			return "loginSuccess";
		}

	}
	
	/**
	 * 3.退出登陆
	 * @return
	 */
	public String logout(){
		HttpSession session = ServletActionContext.getRequest().getSession();
		if(session.getAttribute("existUser") != null){
			session.removeAttribute("existUser");
			session.invalidate();
			return "logoutSuccess";
		}else{
			return ERROR;
		}
	}
	
	/**
	 * 4.跳转到注册页面的方法
	 */
	public String registerPage() {
		return "registerPage";
	}
	
	/**
	 * 5.验证手机号是否已经注册了
	 * @return
	 */
	public String checkRegister(){
		boolean flag = memberService.findByPhoneNumber(telephone);
		if(flag){
			// 已经注册
			response.setResult(Result.SUCCESS.toString());
			response.setMessage("该手机号已经注册过");
			response.setData(flag);
		} else{
			// 未注册
			response.setResult(Result.FAILED.toString());
			response.setMessage("该手机号还未注册过");
			response.setData(flag);
		}
		return "isRegister";	
	}
	
	/**
	 * 6.注册
	 * @return
	 */
	public String register(){
		boolean flag = memberService.addMember(member);
		if(flag){
			// 注册成功
			response.setResult(Result.SUCCESS.toString());
			response.setMessage("注册成功");
			response.setData(flag);
		} else{
			// 注册失败
			response.setResult(Result.FAILED.toString());
			response.setMessage("注册失败");
			response.setData(flag);
		}
		return "toRegister";
	}
	
	/**
	 * 7.分页查询用户
	 * @return
	 */
	public String listPage(){
		String page = ServletActionContext.getRequest().getParameter("page");
		String rows = ServletActionContext.getRequest().getParameter("rows");
		String id = ServletActionContext.getRequest().getParameter("id");
		String nickName = ServletActionContext.getRequest().getParameter("nickName");
		String startDate = ServletActionContext.getRequest().getParameter("startDate");
		String endDate = ServletActionContext.getRequest().getParameter("endDate");
		GridPageBean<Member> listPage = memberService.findByPage(page, rows, id, nickName,startDate, endDate);
		if(listPage!=null && listPage.getRecords()>0){
			response.setResult(Result.SUCCESS.toString());
			response.setMessage("查询成功");
		}else{
			response.setResult(Result.FAILED.toString());
			response.setMessage("查询失败");
		}
		response.setData(listPage);
		return "listPageSUCCESS";
	}
	
	/**
	 * 8.更新用户状态
	 * @return
	 */
	public String updateStatusById(){
		String id = ServletActionContext.getRequest().getParameter("id");
		String status = ServletActionContext.getRequest().getParameter("status");
		try {
			memberService.updateStatus(id, status);
			response.setResult(Result.SUCCESS.toString());
			response.setMessage("操作成功");
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("屏蔽用户发生异常");
			response.setResult(Result.FAILED.toString());
			response.setMessage(e.getMessage());
		}
		return "shieldSUCCESS";
	}
	
	/**
	 * 8.跳转到个人信息页
	 */
	public String toPersonPage() {
		String id=member.getId()+"";
		member=memberService.getMemberById(id);
		return "toPersonPage";
	}
	
	public String checkPassword(){
		boolean flag=memberService.checkPassword(member);
		if(flag){
			response.setMessage("true");
		}else{
			response.setMessage("false");
		}
		return "checkPassword";
	}
	
	public String alterPws(){
		HttpServletRequest request=ServletActionContext.getRequest();
		String memId=request.getParameter("memId");
		String newPws=request.getParameter("newPws");
		boolean flag=memberService.alterPws(memId, newPws);
		if(flag){
			response.setMessage("true");
		}else{
			response.setMessage("false");
		}
		return "alterPws";
	}
	
	public String pushPortrait(){
		System.out.println("进入");
		/*HttpServletRequest request = ServletActionContext.getRequest();
		String root = request.getRealPath("/img/portrait");//图片要上传到的服务器路径
		String names[]=portraitFileName.split("\\.");
		String fileName="";
		if(names.length>=1){
			fileName=getRandomString(10)+"."+names[names.length-1]; //重构文件名，防止重名
		}
		String picPath="img/portrait/"+fileName;//图片保存到数据库的路径
		File file=new File(root);
		try {
			FileUtils.copyFile(portrait, new File(file,fileName));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		boolean flag=memberService.uploadPic(member.getId(), picPath);
		if(flag){
			response.setMessage("success");
		}		*/
		return "pushPortrait";
	}
	
	public String getCollections(){
		HttpServletRequest request=ServletActionContext.getRequest();
		pageNum=request.getParameter("pageNum");
		pageBean=memberService.getCollections(member.getId(), pageNum);
		String commId="";
		String memId="";
		for(int i=0;i<pageBean.getRecords().size();i++){
			favo=(Favorite) pageBean.getRecords().get(i);
			commId=favo.getCommodityId()+"";
			logger.info(commId);
			comm=commodityInfoService.getCommById(commId);		
			memId=comm.getMemberId()+"";
			logger.info(memId);
			member=memberService.getMemberById(memId);
			memComm=new MemCommoBean(member,comm,favo);
			System.out.println(memComm.toString());
			memComms.add(memComm);
		}
		return "getCollections";
	}
	
	public String deleteCollect(){
		HttpServletRequest request=ServletActionContext.getRequest();
		boolean flag=memberService.deleteCollect(favo.getId());
		if(flag){
			deleteMsg="删除成功！";
		}
		return "deleteCollect";
	}
	
	
	/*获取一条随机字符串*/
	public String getRandomString(int length) { //length表示生成字符串的长度  
	    String base = "abcdefghijklmnopqrstuvwxyz0123456789";     
	    Random random = new Random();     
	    StringBuffer sb = new StringBuffer();     
	    for (int i = 0; i < length; i++) {     
	        int number = random.nextInt(base.length());     
	        sb.append(base.charAt(number));     
	    }     
	    return sb.toString();     
	 }
}
